﻿using System;
using System.Collections.Generic;
using System.Linq;
using Contracts.Entities;
using Model.WebImport;
using NLog;

namespace Definition.WebImport
{
    public class TmdbImport
    {
        protected Logger logger = LogManager.GetCurrentClassLogger();

        private TmdbGetMovieRequest getMovie;
        private WriteTmdbMovie writer;
        private TmdbGetCover getCover;
        private TmdbGetBackdrops getBackdrops;

        public TmdbImport()
        {
            this.getMovie = new TmdbGetMovieRequest();
            this.writer = new WriteTmdbMovie();           
            this.getCover = new TmdbGetCover();
            this.getBackdrops = new TmdbGetBackdrops();
        }

        /// <summary>
        /// MovieItems mit TmdbId
        /// für doppelte Filme wird nur ein Web Request ausgeführt
        /// Filminfo wird für alle doppelten Filme importiert 
        /// </summary>
        public void Process(IEnumerable<MovieItem> items)
        {
            var requestItems = items.Distinct(new MovieItemTmdbIdComparer());
            var response = new TmdbResult();

            foreach (var item in requestItems)                  
            {
                try
                {
                    response.Request = item.Name;

                    logger.Debug(String.Format("Try import infos for movie {0}", item.Name));

                    var movie = getMovie.Request(item.TmdbId);

                    if (movie == null)
                        throw new ArgumentNullException("Movie is null");

                    foreach (var movieItem in items.Where(m => m.TmdbId == item.TmdbId))
                    {
                        var cover = getCover.Find(movie.Images);
                        var backdrops = getBackdrops.Find(movie.Images);

                        writer.Update(movie, movieItem.Id, cover, backdrops);
                    }

                    response.Success = true;
                }
                catch (Exception e)
                {
                    logger.Error(e.Message);
                }
                finally
                {
                    OnResult(response);
                }
            }
        }

        public event Action<TmdbResult> OnResult = delegate { };
    }
}
